package com.lagou.service.impl;

import com.lagou.common.ResponseCode;
import com.lagou.common.ResponseResult;
import com.lagou.feign.EmailServiceFeignClient;
import com.lagou.service.CodeService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class CodeServiceImpl implements CodeService {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private EmailServiceFeignClient emailServiceFeignClient;

    //验证码过期时间(单位:s)
    @Value("${codeTimeout:300}")
    private Integer codeTimeout;

    @Override
    public Boolean createCode(String email) {
        // 随机6位数验证码
        int code = (int) ((Math.random() * 9 + 1) * 100000);
        // 保存redis, 过期5min
        redisTemplate.opsForValue().set(email, String.valueOf(code), codeTimeout, TimeUnit.SECONDS);

        // 发送邮件
        ResponseResult<Boolean> res = emailServiceFeignClient.sendEmail(email, String.valueOf(code));

        if (null == res || !res.getCode().equalsIgnoreCase(ResponseCode.SUCCESS)) {
            throw new RuntimeException("发送邮件失败");
        }
        return true;
    }

    /**
     * 0正确 1错误 2超时
     *
     * @param email
     * @param code
     * @return
     */
    @Override
    public Integer validateCode(String email, String code) {
        String s = redisTemplate.opsForValue().get(email);
        if (StringUtils.isBlank(s)) {
            return 2;
        }
        if (s.equalsIgnoreCase(code)) {
            return 0;
        } else {
            return 1;
        }
    }
}
